package com.panda.mall.order.info.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.panda.mall.common.constants.ConfigConstants;
import com.panda.mall.common.mallElastic.feign.ElasticFeign;
import com.panda.mall.common.mallOrder.dto.QueryOrderDto;
import com.panda.mall.common.mallOrder.entity.MallOrder;
import com.panda.mall.common.mallOrder.enums.OrderStatusEnum;
import com.panda.mall.common.result.ServiceException;
import com.panda.mall.order.info.service.MallOrderService;
import com.panda.mall.order.info.mapper.MallOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
* @author tucy123
* @description 针对表【mall_order(订单信息表)】的数据库操作Service实现
* @createDate 2022-10-13 16:33:08
*/
@Service
public class MallOrderServiceImpl extends ServiceImpl<MallOrderMapper, MallOrder> implements MallOrderService{

    @Autowired
    MallOrderMapper mallOrderMapper;

    @Autowired
    ElasticFeign elasticFeign;

    /**
     * 获取订单编号
     * @return
     */
    @Override
    public String generateOrderNumber() {

        String orderNumber = this.orderNumber();

        //重复查询
        QueryWrapper<MallOrder> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MallOrder::getOrderNumber, orderNumber);
        Long count = mallOrderMapper.selectCount(wrapper);

        if (count > 0) {
            for (int j = 0; j < 8999999; j++) {
                String newNumber = this.orderNumber();
                wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(MallOrder::getOrderNumber, newNumber);
                if (mallOrderMapper.selectCount(wrapper) == 0) {
                    return orderNumber;
                }
            }
            throw new ServiceException("订单编号生成异常");
        }
        return orderNumber;

    }

    public String orderNumber(){
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String now = format.format(new Date());
        Integer code = UUID.randomUUID().toString().split("-").hashCode();
        String number = String.format("%010d", code).substring(0, 4);

        //订单编号
        return "DDH" + now + number;
    }

    /**
     * 分页查询订单
     * @return
     */
    @Override
    public Page<MallOrder> listOrders(QueryOrderDto dto) {

        Page<MallOrder> page = new Page<>(dto.getPageNum(),dto.getPageSize());

        QueryWrapper<MallOrder> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ObjectUtil.isNotEmpty(dto.getOrderNumber()),MallOrder::getOrderNumber,dto.getOrderNumber())
                .eq(ObjectUtil.isNotEmpty(dto.getUserName()),MallOrder::getUserName,dto.getUserName())
                .eq(ObjectUtil.isNotEmpty(dto.getPayType()),MallOrder::getPayType,dto.getPayType())
                .eq(ObjectUtil.isNotEmpty(dto.getSourceType()),MallOrder::getSourceType,dto.getSourceType())
                .eq(ObjectUtil.isNotEmpty(dto.getOrderStatus()),MallOrder::getOrderStatus,dto.getOrderStatus())
                .eq(ObjectUtil.isNotEmpty(dto.getDeliveryCompany()),MallOrder::getDeliveryCompany,dto.getDeliveryCompany())
                .eq(ObjectUtil.isNotEmpty(dto.getDeliveryNumber()),MallOrder::getDeliveryNumber,dto.getDeliveryNumber())
                .eq(ObjectUtil.isNotEmpty(dto.getBillType()),MallOrder::getBillType,dto.getBillType())
                .eq(ObjectUtil.isNotEmpty(dto.getReceiverName()),MallOrder::getReceiverName,dto.getReceiverName())
                .eq(ObjectUtil.isNotEmpty(dto.getReceiverPhone()),MallOrder::getReceiverPhone,dto.getReceiverPhone())
                .eq(ObjectUtil.isNotEmpty(dto.getConfirmStatus()),MallOrder::getConfirmStatus,dto.getConfirmStatus());

        return mallOrderMapper.selectPage(page,wrapper);
    }

    /**
     * 查询订单
     * @return
     */
    @Override
    public List<MallOrder> queryOrders() {
        return this.list();
    }

    /**
     * 按id查询订单
     * @param id
     * @return
     */
    @Override
    public MallOrder queryOrderById(Long id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * 新增订单
     * @param order
     * @return
     */
    @Override
    public Boolean saveOrder(MallOrder order) {
        //订单编号
        order.setOrderNumber(this.generateOrderNumber());
        boolean save = this.saveOrUpdate(order);
        if (save){
            Long id = order.getId();
            String index = ConfigConstants.INDEX_order;
            elasticFeign.addDocument(id,index);
        }
        return save;
    }

    /**
     * 修改订单
     * @param order
     * @return
     */
    @Override
    public Boolean updateOrder(MallOrder order) {
        MallOrder mallOrder = this.lambdaQuery().eq(MallOrder::getId, order.getId()).one();
        if (!mallOrder.getOrderStatus().equals(OrderStatusEnum.WAITPAY.getValue()) &&
                !mallOrder.getOrderStatus().equals(OrderStatusEnum.WAITGOODS.getValue())){
            throw new ServiceException("订单无法修改");
        }
        boolean update = this.saveOrUpdate(order);
        if (update){
            Long id = order.getId();
            String index = ConfigConstants.INDEX_order;
            elasticFeign.addDocument(id,index);
        }
        return update;
    }

    @Override
    public String deleteOrder(List<Long> ids) {
        mallOrderMapper.deleteOrder(ids);
        return "删除成功";
    }


}
